from common.pagenation import Paging
from daos import get_db_session, get_update_contents
from models.image_library import ImageLibrary


def add_image_library(log_orm: ImageLibrary, is_commit=True):
    session = get_db_session()

    session.add(log_orm)
    session.commit() if is_commit else session.flush()
    return log_orm


def query_image_library(pk):
    return get_db_session().query(ImageLibrary).filter(ImageLibrary.id == pk).first()


def query_image_library_by_title(title):
    return get_db_session().query(ImageLibrary).filter(ImageLibrary.title == title).first()


def update_image_library(user_orm: ImageLibrary, *args, is_commit=True):
    session = get_db_session()
    update_contents = get_update_contents(user_orm, *args)
    session.query(ImageLibrary).filter(ImageLibrary.id == user_orm.id).update(update_contents)
    session.commit() if is_commit else session.flush()
    return


def query_image_library_with_page(data_param):
    filter_s = []

    if data_param.get('title'):
        filter_s.append(ImageLibrary.title.contains(data_param.get('title')))

    if data_param.get('dy_open_pic_id'):
        filter_s.append(ImageLibrary.dy_open_pic_id == data_param.get('dy_open_pic_id'))

    if data_param.get('status'):
        filter_s.append(ImageLibrary.status == data_param.get('status'))

    session = get_db_session()
    return session.query(ImageLibrary) \
        .filter(*filter_s) \
        .order_by(ImageLibrary.id.desc()) \
        .paginate(page=data_param.get('page'), per_page=data_param.get('page_size'), error_out=False)


def query_image_library_s(data_param):
    filter_s = []

    if data_param.get('title'):
        filter_s.append(ImageLibrary.title.contains(data_param.get('title')))

    if data_param.get('dy_open_pic_id'):
        filter_s.append(ImageLibrary.dy_open_pic_id == data_param.get('dy_open_pic_id'))

    if data_param.get('status'):
        filter_s.append(ImageLibrary.status == data_param.get('status'))

    session = get_db_session()
    return session.query(ImageLibrary) \
        .filter(*filter_s) \
        .order_by(ImageLibrary.id.desc()) \
        .all()


def query_image_library_count(data_param):
    filter_s = []

    if data_param.get('title'):
        filter_s.append(ImageLibrary.title == data_param.get('title'))

    if data_param.get('dy_open_pic_id'):
        filter_s.append(ImageLibrary.dy_open_pic_id == data_param.get('dy_open_pic_id'))

    if data_param.get('status'):
        filter_s.append(ImageLibrary.status == data_param.get('status'))

    session = get_db_session()
    return session.query(ImageLibrary).filter(*filter_s).count()
